﻿using System;
using System.Diagnostics;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;

namespace NHibernate
{

  public abstract class NHTestFixtureBase
  {

    protected NHTestFixtureBase()
    {
      ConfigureSessionFactory();
      ConfigureProfiler();
    }

    private ISessionFactory SessionFactory { get; set; }

    void ConfigureSessionFactory()
    {
      this.SessionFactory = Fluently.Configure()
        .Database
        (
          SQLiteConfiguration.Standard
            .ConnectionString(c => c.FromAppSetting("sqlite-connection-string"))
            .ProxyFactoryFactory(typeof(NHibernate.ByteCode.LinFu.ProxyFactoryFactory).AssemblyQualifiedName)
            .DefaultSchema("")
            .AdoNetBatchSize(100)
        )
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHTestFixtureBase>())
        .ExposeConfiguration
        (
          configuration =>
            {
#if DEBUG
              configuration.SetProperty("generate_statistics", "true");
#endif
              var exporter = new SchemaExport(configuration);
              exporter.Execute(false, true, false);
            }          
        )
        .BuildSessionFactory();
    }

    [Conditional("DEBUG")]
    public void ConfigureProfiler()
    {
      //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
    }

    public ISession CreateSession()
    {
      return this.SessionFactory.OpenSession();
    }

    public void ExecuteInSessionTransaction(Func<ISession, bool> action)
    {
      using(ISession session = CreateSession())
      {
        using(ITransaction transaction = session.BeginTransaction())
        {
          try
          {
            if (action(session))
              transaction.Commit();
            else
              transaction.Rollback();
          }
          catch
          {
            transaction.Rollback();
            throw;
          }
        }
      }
    }

  }

}
